from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from login_api.models import CheckUserName, User
# Create your views here.


def getInfos(request):
    if request.method == 'GET':   # GET 请求，从后端获取用户名，账号两个信息
        all_values = CheckUserName.objects.all().values()
        print(list(all_values))
        data = dict()
        data['data'] = list(all_values)
        return JsonResponse(data, safe=True)


@csrf_exempt
def Register(request):
    t = json.loads(request.body)
    print(t)
    if request.method == 'POST':   # 若是post请求，表示是注册
        req = json.loads(request.body)
        user = req['user']
        name = req['name']
        if User.objects.filter(user=user, name=name):   # 若找到了
            return JsonResponse({"status": 500, "message": "注册失败!"})
        password = req['password']
        email = req['email']
        new_user = User(user, name, password, email)
        new_user.save()
        return JsonResponse({"status": 200, "message":"注册成功!"})


@csrf_exempt
def Login(request):
    if request.method == "POST":
        req = json.loads(request.body)
        user = req['user']
        password = req['password']
        t1 = User.objects.filter(user=user, password=password)
        t2 = User.objects.filter(user=user)
        t3 = t2.filter(password=password)
        print(t1, t2, t3)
        if len(t1) == 1:
            return JsonResponse({"status": 200, "message": "登陆成功!"})
        else:
            if len(t2) == 0:  # 如果没找到账号，则表示账号不存在
                return JsonResponse({"status": 404, "message": "账号不存在!"})
            if len(t3) == 0:  # 如果账号存在，密码错误
                return JsonResponse({"status": 405, "message": "密码错误!"})